<template>
  <div class="addPicturePage">
    <h2 style="margin-bottom: 16px">
      {{ route.query?.id ? '编辑图片' : '创建图片' }}
    </h2>
    <a-typography-paragraph v-if="spaceId" type="secondary">
      保存至空间：<a :href="`/space/${spaceId}`" target="_blank">{{ spaceId }}</a>
    </a-typography-paragraph>
    <!-- 上传图片组件 -->
    <Suspense>
      <template v-if="route.query?.id">
        <PictureUpload v-show="isLoaded" :picture="picture" :onSuccess="onSuccess"></PictureUpload>
        <!-- 编辑图片 -->
        <div v-if="picture" class="edit-bar">
          <a-space size="middle">
            <a-button :icon="h(EditOutlined)" @click="doEditPicture">编辑图片</a-button>
            <a-button type="primary" ghost :icon="h(FullscreenOutlined)" @click="doImagePainting">
              AI 扩图
            </a-button>
          </a-space>
          <ImageCropper
            ref="imageCropperRef"
            :imageUrl="picture?.url"
            :picture="picture"
            :spaceId="spaceId"
            :onSuccess="onCropSuccess"
          />
          <ImageOutPainting
            ref="imageOutPaintingRef"
            :picture="picture"
            :spaceId="spaceId"
            :onSuccess="onImageOutPaintingSuccess"
          />
        </div>
      </template>
      <template v-else>
        <a-tabs v-model:activeKey="fileUploadType">
          <a-tab-pane key="file" tab="文件上传">
            <!-- 文件上传 -->
            <PictureUpload :picture="picture" :spaceId="spaceId" :onSuccess="onSuccess" />
          </a-tab-pane>
          <a-tab-pane key="url" tab="Url 上传" force-render>
            <!-- Url上传 -->
            <PictureUrlUpload
              :pictureUrl="pictureUrl"
              :spaceId="spaceId"
              :onSuccess="onSuccessUrl"
            />
          </a-tab-pane>
        </a-tabs>
        <!-- 编辑图片 -->
        <div v-if="picture" class="edit-bar">
          <a-space size="middle">
            <a-button :icon="h(EditOutlined)" @click="doEditPicture">编辑图片</a-button>
            <a-button type="primary" ghost :icon="h(FullscreenOutlined)" @click="doImagePainting">
              AI 扩图
            </a-button>
          </a-space>
          <ImageCropper
            ref="imageCropperRef"
            :imageUrl="picture?.url"
            :picture="picture"
            :spaceId="spaceId"
            :onSuccess="onCropSuccess"
          />
          <ImageOutPainting
            ref="imageOutPaintingRef"
            :picture="picture"
            :spaceId="spaceId"
            :onSuccess="onImageOutPaintingSuccess"
          />
        </div>
        <!-- 编辑图片 -->
        <div v-if="pictureUrl" class="edit-bar">
          <a-space size="middle">
            <a-button :icon="h(EditOutlined)" @click="doEditPicture">编辑图片</a-button>
            <a-button type="primary" ghost :icon="h(FullscreenOutlined)" @click="doImagePainting">
              AI 扩图
            </a-button>
          </a-space>
          <ImageCropper
            ref="imageCropperRef"
            :imageUrl="picture?.url"
            :picture="picture"
            :spaceId="spaceId"
            :onSuccess="onCropSuccess"
          />
          <ImageOutPainting
            ref="imageOutPaintingRef"
            :picture="picture"
            :spaceId="spaceId"
            :onSuccess="onImageOutPaintingSuccess"
          />
        </div>
      </template>
    </Suspense>
    <template v-if="fileUploadType === 'file' && picture">
      <a-form layout="vertical" :model="pictureForm" @finish="handleSubmit">
        <a-form-item label="名称" name="name">
          <a-input v-model:value="pictureForm.name" placeholder="请输入名称" />
        </a-form-item>
        <a-form-item label="简介" name="introduction">
          <a-textarea
            v-model:value="pictureForm.introduction"
            placeholder="请输入简介"
            :auto-size="{ minRows: 3, maxRows: 5 }"
            allowClear
          />
        </a-form-item>
        <a-form-item label="分类" name="category">
          <a-auto-complete
            v-model:value="pictureForm.category"
            mode="category"
            placeholder="请输入分类"
            :options="categoryList"
            allowClear
          />
        </a-form-item>
        <a-form-item label="标签" name="tags">
          <a-select
            v-model:value="pictureForm.tags"
            mode="tags"
            placeholder="请输入标签"
            :options="tagList"
            allowClear
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit" style="width: 100%; margin-bottom: 16px"
            >创建
          </a-button>
        </a-form-item>
      </a-form>
    </template>
    <template v-if="fileUploadType === 'url' && pictureUrl">
      <a-form layout="vertical" :model="pictureForm" @finish="handleSubmit">
        <a-form-item label="名称" name="name">
          <a-input v-model:value="pictureForm.name" placeholder="请输入名称" />
        </a-form-item>
        <a-form-item label="简介" name="introduction">
          <a-textarea
            v-model:value="pictureForm.introduction"
            placeholder="请输入简介"
            :auto-size="{ minRows: 3, maxRows: 5 }"
            allowClear
          />
        </a-form-item>
        <a-form-item label="分类" name="category">
          <a-auto-complete
            v-model:value="pictureForm.category"
            mode="category"
            placeholder="请输入分类"
            :options="categoryList"
            allowClear
          />
        </a-form-item>
        <a-form-item label="标签" name="tags">
          <a-select
            v-model:value="pictureForm.tags"
            mode="tags"
            placeholder="请输入标签"
            :options="tagList"
            allowClear
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit" style="width: 100%; margin-bottom: 16px"
            >创建
          </a-button>
        </a-form-item>
      </a-form>
    </template>
    <!-- 上传图片表单 -->
  </div>
</template>

<script lang="ts" setup>
import PictureUpload from '@/components/PictureUpload.vue'
import { computed, onMounted, reactive, ref, h } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  editPictureUsingPost,
  getPictureByIdUsingGet,
  listPictureTagCategoryUsingGet,
} from '@/apis/PictureInterface.ts'
import { message } from 'ant-design-vue'
import PictureUrlUpload from '@/components/PictureUrlUpload.vue'
import { EditOutlined, FullscreenOutlined } from '@ant-design/icons-vue'
import ImageCropper from '@/components/ImageCropper.vue'
import ImageOutPainting from '@/components/ImageOutPainting.vue'

const fileUploadType = ref('file', 'url')

const isLoaded = ref(false)

const picture = ref<API.PictureVO>()
const pictureUrl = ref<API.PictureVO>()

// 上传图片表单信息
const pictureForm = reactive<API.PictureEditRequest>({})
const onSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
  // 将图片的名字填充到表单中
  pictureForm.name = newPicture.name
  getPicture()
}

const onSuccessUrl = (newPicture: API.PictureVO) => {
  pictureUrl.value = newPicture
  // 将图片的名字填充到表单中
  pictureForm.name = newPicture.name
}

// 空间 id,上传图片时需要携带
const spaceId = computed(() => {
  return route.query?.spaceId
})

/**
 * 提交表单
 * @param values
 */
const router = useRouter()
const handleSubmit = async (values: any) => {
  const pictureId = picture.value?.id || pictureUrl.value?.id
  if (!pictureId) {
    return
  }
  const res = await editPictureUsingPost({
    id: pictureId,
    spaceId: spaceId.value,
    ...values,
  })
  if (res.data.code === 0 && res.data.data) {
    message.success('创建成功')
    // 跳转到图片详情页
    router.push({
      path: `/picture/${pictureId}`,
    })
  } else {
    message.error('创建失败，' + res.data.message)
  }
}

/**
 * 调用后端获取tag和分类
 */
const categoryList = ref<string[]>([])
const tagList = ref<string[]>([])
const getTagAndCategory = async () => {
  try {
    const res = await listPictureTagCategoryUsingGet()
    if (res.data.code === 0 && res.data.data) {
      categoryList.value = (res.data.data.categoryList ?? []).map((data: string) => {
        // 由于下拉框需要数据类型为{
        //   value: string
        //   label: string
        // }
        // 所以需要遍历并以对象的形式返回
        return {
          value: data,
          label: data,
        }
      })
      tagList.value = (res.data.data.tagList ?? []).map((data: string) => {
        return {
          value: data,
          label: data,
        }
      })
    } else {
      message.error('获取标签和分类失败，' + res.data.message)
    }
  } catch (error) {
    message.error('获取标签和分类失败', error.message)
  }
}
onMounted(() => {
  getTagAndCategory()
})

/**
 * 先获取图片信息，然后进行编辑
 */
// 获取路由参数，比如说路由信息为 ?id=1213123123
const route = useRoute()
// 调用后端获取图片信息
const getPicture = async () => {
  try {
    const pictureId = route.query?.id
    const res = await getPictureByIdUsingGet({
      pictureId: pictureId,
    })
    if (res.data.code === 0 && res.data.data) {
      const data = res.data.data
      picture.value = data
      pictureForm.name = data.name
      pictureForm.introduction = data.introduction
      pictureForm.category = data.category
      pictureForm.tags = data.tags
    }
  } catch (error) {
    message.error('获取图片信息失败', error.message)
  }
  isLoaded.value = true
}
onMounted(() => {
  getPicture()
})

// 图片编辑弹窗引用
const imageCropperRef = ref()

// 编辑图片
const doEditPicture = () => {
  if (imageCropperRef.value) {
    imageCropperRef.value.openModal()
  }
}

// 编辑成功事件
const onCropSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}

// AI 扩图弹窗引用
const imageOutPaintingRef = ref()

// AI 扩图
const doImagePainting = () => {
  if (imageOutPaintingRef.value) {
    imageOutPaintingRef.value.openModal()
  }
}

// 编辑成功事件
const onImageOutPaintingSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}
</script>

<style scoped>
.addPicturePage {
  max-width: 720px;
  margin: 0 auto;
}

.addPicturePage .edit-bar {
  text-align: center;
  margin: 5px 0;
}
</style>
